package com.astrocsr.action.common;
 
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.astrocsr.action.BaseAction;
import com.astrocsr.business.AuditLogManager;
import com.astrocsr.business.StatementManager;
import com.astrocsr.business.UserManager;
import com.astrocsr.common.Constants;
import com.astrocsr.common.EbppKeys;
import com.astrocsr.common.helper.ConfigHelper;
import com.astrocsr.common.helper.ContextHelper;
import com.astrocsr.common.helper.EncryptionHelper;
import com.astrocsr.common.util.DateUtil;
import com.astrocsr.domain.model.DownloadModel;
import com.opensymphony.xwork2.ModelDriven;

@Controller("downloadAction")
@Scope("prototype")
public class DownloadAction extends BaseAction implements ModelDriven<DownloadModel>, 
	ServletContextAware {

	private static final long serialVersionUID = 1L;
	static final Logger log = Logger.getLogger(DownloadAction.class);
    static final SimpleDateFormat dateFormatterIn 	= new SimpleDateFormat("yyyy-MM-dd");
    static final SimpleDateFormat dateFormatterOut 	= new SimpleDateFormat("dd/MM/yy");
    
	private DownloadModel model = new DownloadModel();
	private InputStream fileInputStream;
	private String fileName;
 
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private StatementManager statementManager;
	@Autowired
	private AuditLogManager auditLogManager; 

	@Override
	public DownloadModel getModel() {
		return model;
	}
	public InputStream getFileInputStream() {
		return fileInputStream;
	}
	public String getFileName() {
		return fileName;
	}

	/**
	 * download pdf
	 */
	public String execute() throws Exception {
		try {

			String realPath = context.getRealPath("") + File.separator;
			final String resourcePath = realPath + "resource" + File.separator;
			System.out.println("resourcePath = " + resourcePath);

			String stmtDate = model.getStmtdate();
			String groupCode = model.getGroupCode();
			
			if (StringUtils.isNotBlank(stmtDate)){
				stmtDate = EncryptionHelper.decrypt(stmtDate, ConfigHelper.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
				log.info("PDFDownload_encrypted StmtDate" + stmtDate);
			}

			if (StringUtils.isNotBlank(groupCode)){
				groupCode = EncryptionHelper.decrypt(groupCode, ConfigHelper.getInstance().get(EbppKeys.ENCRYPTION_PASSPHRASE));
				log.info("PDFDownload_encrypted groupCode" + groupCode);
			}

			if (StringUtils.isNotBlank(groupCode) && StringUtils.isNotBlank(stmtDate)) {
				Date statementDate = DateUtil.createDateLocalSlash(stmtDate);
				fileName = groupCode + "_" + DateUtil.formatUniversal(statementDate) + ".pdf";
	            
	    		byte[] outBytes = statementManager.getPDFData(groupCode, statementDate, resourcePath);
	            fileInputStream = new ByteArrayInputStream(outBytes);
	            
				// insert log
				auditLogManager.addAuditlog(
						Constants.LOG_ACCT_TYPE_ACTIVITY,	//0
						Constants.LOG_ActCode_Bill_Download, 	//1 
						Constants.LOG_ActName_Bill_Download, 	//2
						ContextHelper.getLoginId(), 		//3
						ContextHelper.getCurrentRole(), 	//4
						"Bill Download; stmtDate: " + stmtDate, //5
						request.getRemoteAddr()				//6
						);
			}

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return SUCCESS;
	}
	
	private ServletContext context;
    @Override
    public void setServletContext(ServletContext ctx) {
        this.context=ctx;
    }
}